<template>
	<!-- <view v-if="loaded" class="container"> -->
	<view :id="templateId" class="container tabbar-page">
		<!-- 商品列表 -->
		<!-- <template v-if="loaded"> -->
		<template>
			<empty
				v-if="loaded && !cartList.length"
				:src="baseTemplateFileUri + 'image/emptyStatus/common.png'"
				size="small"
				desc="购物车是空的哦 ~"
			></empty>
			<view v-if="cartList.length" class="cart-wrap">
				<!-- <view class="tis" v-if="cartList.length == 0">购物车是空的哦 ~</view> -->
				<view v-for="(item, index) in cartList" :key="item.cartId">
					<view class="cart-wrap__goods">
						<!-- 删除按钮 begin -->
						<view
							:style="themeStyles.btnFullColor"
							class="menu"
							@tap.stop="onDeleteCustomerCart(item.cartId, index)"
						>
							<view class="icon shanchu">删除</view>
						</view>
						<!-- 删除按钮 end -->

						<!-- 商品 begin -->
						<view
							class="carrier"
							:class="[
								theIndex == index
									? 'open'
									: oldIndex == index
									? 'close'
									: ''
							]"
							@touchstart="touchStart(index, $event)"
							@touchmove="touchMove(index, $event)"
							@touchend="touchEnd(index, $event)"
						>
							<!-- checkbox begin -->
							<view
								class="checkbox-box"
								@tap="selectedCart(item)"
							>
								<view
									v-if="item.isEffective !== 1"
									class="lapse checkbox"
									>商<br />品<br />失<br />效</view
								>
								<view
									v-else
									class="checkbox"
									:class="{ checked: item.checked }"
								>
									<!-- 主题色 -->
									<uni-icon
										size="40rpx"
										:color="
											(item.checked &&
												themeStyles.lightMainColor) ||
												'#999999'
										"
										:name="
											item.checked ? 'hook-full' : 'hook'
										"
									>
									</uni-icon>
								</view>
							</view>
							<!-- checkbox end -->
							<uni-goods-col
								:goods="item"
								:routeLink="
									item.isEffective === 1 &&
										`/pages/common/pages/goods/goodsDetail?goodsId=${item.goodsId}`
								"
								:goodsPrice="item.priceStr.split('.')"
								:goodsTypeText="item.skuName"
								:priceColor="themeStyles.mainColor"
							>
								<!-- 购买按钮 begin -->

								<!-- 主题色 -->
								<template slot="metaRight">
									<text
										v-if="item.isEffective !== 1"
										class="cut-num"
										>x{{ item.number }}</text
									>
									<view
										v-else
										@tap.stop="stopBubble()"
										class="df df-r buy-number-input"
									>
										<view
											class="df df-r sub"
											@tap.stop="subBuyNum(index)"
											>-</view
										>
										<view class="df df-c input-box">
											<input
												disabled
												class="tac input"
												type="number"
												v-model="item.number"
												@blur="ranDomBuyNum(index)"
											/>
										</view>
										<view
											class="df df-r add"
											@tap.stop="addBuyNum(index)"
											>+</view
										>
									</view>
								</template>
								<!-- 购买按钮 end -->
							</uni-goods-col>
						</view>
						<!-- 商品 end-->
					</view>
				</view>
			</view>
			<!-- 精选推荐 begin -->
			<view v-if="goodsList.length" class="choice">
				<view class="choice__title">
					<trick-title
						title="为您推荐"
						iconName="love"
						:color="themeStyles.mainColor"
						:iconColor="themeStyles.lightMainColor"
					>
					</trick-title>
				</view>
				<view class="choice__goods">
					<uni-goods-list :goodsList="goodsList"> </uni-goods-list>
				</view>
				<uni-load-more :status="loadingType"> </uni-load-more>
			</view>
			<!-- 精选推荐 end -->
			<!-- 脚部菜单 -->
			<view
				v-if="cartList.length"
				class="footer-wrap"
				:style="{ bottom: footerbottom }"
			>
				<view class="checkbox-box" @tap="allSelectGoods">
					<view class="checkbox" :class="{ checked: isAllselected }">
						<!-- 主题色 -->
						<uni-icon
							size="40rpx"
							:color="
								(isAllselected && themeStyles.lightMainColor) ||
									'#999999'
							"
							:name="isAllselected ? 'hook-full' : 'hook'"
						>
						</uni-icon>
					</view>
					<view class="text">全选</view>
				</view>
				<view
					:style="themeStyles.btnGhostColor"
					class="delete-btn"
					@tap="onDeleteCustomerCart()"
					v-if="selectedList.length > 0"
					>删除</view
				>
				<view class="settlement">
					<!-- 主题色 -->
					<view :style="themeStyles.textMainColor" class="sum">
						<!-- <text class="tip">￥</text> -->
						<text class="price">{{ priceTotal[0] || "0" }}</text>
						<text class="decimal">{{ priceTotal[1] || "00" }}</text>
					</view>
					<!-- 主题色 -->
					<view
						:style="themeStyles.btnFullColor"
						class="btn"
						@tap="toConfirmation()"
						>结算({{ selectedList.length }})</view
					>
				</view>
			</view>
		</template>

		<uni-tabbar
			@onClick="switchTabbar"
			:animationData="animationData"
			:badgeBg="themeStyles.lightMainColor"
			:tintColor="themeStyles.mainColor"
		></uni-tabbar>
	</view>
</template>

<script>
import {
	queryCartList,
	updateCart,
	deleteBatchCart,
	queryPriceTotal
} from "@/lib/api/interestedServer/cart";

import { baseFileUri } from "@/utils/request/baseConfig";

/** components begin */
import uniTabbar from "@/components/uniTabbar";
import uniGoodsList from "@/components/goods/uniGoodsList";
import uniGoodsCol from "@/components/goods/uniGoodsCol";
import trickTitle from "@/components/trickTitle/trickTitle";
import empty from "@/components/empty";
import uniIcon from "@/components/uniIcon/uniIcon";
import uniLoadMore from "@/components/uniLoadMore/uniLoadMore";

/** components end */

/** mixins beagin */
import goodsMixin from "@/mixins/goods/goods";
import tabbarMixin from "@/mixins/tabbar";
/** mixins end */

/** localData begin */
let goodsCurrentPage = 1;

/** localData end */
export default {
	mixins: [goodsMixin, tabbarMixin],
	components: {
		uniTabbar,
		trickTitle,
		uniGoodsCol,
		uniGoodsList,
		uniLoadMore,
		empty,
		uniIcon
	},
	data() {
		return {
			baseFileUri,
			currentGoodsIndex: null,
			sumPrice: "0",
			sumPriceDecimal: "00",
			headerPosition: "fixed",
			headerTop: null,
			statusTop: null,
			showHeader: true,
			selectedList: [],
			isAllselected: false,
			priceTotal: null,
			cartList: [],
			//控制滑动效果
			theIndex: null,
			oldIndex: null,
			isStop: false
		};
	},

	onLoad() {
		goodsCurrentPage = 1;
		this.getGoodsListAll({
			currentPage: goodsCurrentPage,
			showLoading: false,
			hideLoading: false
		});
	},

	async onShow() {
		// Object.assign(this.$data, this.$options.data());
		uni.showLoading();
		this.isAllselected = false;
		await this.getCartList();
		this.allSelectGoods();

		// goodsCurrentPage = 1;
		// this.getGoodsListAll({
		//     currentPage: 1,
		//     showLoading: false,
		//     hideLoading: false
		// });
	},

	onPageScroll(e) {
		//兼容iOS端下拉时顶部漂移
		this.headerPosition = e.scrollTop >= 0 ? "fixed" : "absolute";
		this.headerTop = e.scrollTop >= 0 ? null : 0;
		this.statusTop = e.scrollTop >= 0 ? null : -this.statusHeight + "px";
	},

	//下拉刷新
	async onPullDownRefresh() {
		Object.assign(this.$data, this.$options.data());
		uni.showLoading();
		await this.getCartList();
		this.allSelectGoods();

		goodsCurrentPage = 1;
		this.getGoodsListAll({
			currentPage: goodsCurrentPage,
			showLoading: false
		});
	},

	// 上拉加载
	onReachBottom() {
		console.log("this.loadingType", this.loadingType);
		if (this.loadingType === "more") {
			goodsCurrentPage++;
			this.getGoodsListAll({
				currentPage: goodsCurrentPage,
				showLoading: false
			});
		}
	},

	methods: {
		// 计算购物车总价
		async calcPriceTotal() {
			const propsData = {
				cartIds: this.selectedList.join(","),
				showLoading: false
			};
			try {
				const res = await queryPriceTotal(propsData);
				this.priceTotal = `${res.data.priceTotal}`.split(".");
			} catch (error) {
				console.log("queryPriceTotalError", error);
				this.$api.showToast(error.resultInfo || "操作失败");
			}
		},

		// 查询购物车商品
		async getCartList() {
			const propsData = {
				showLoading: false,
				hideLoading: false
			};

			try {
				const { data } = await queryCartList(propsData);
				this.cartList = data.list;
				uni.stopPullDownRefresh();
				this.loaded = true;
			} catch (error) {
				console.log("error", error);
				this.loaded = true;
				uni.stopPullDownRefresh();
			}
		},

		/** 控制左滑删除效果 begin */
		touchStart(index, event) {
			//多点触控不触发
			if (event.touches.length > 1) {
				this.isStop = true;
				return;
			}
			this.oldIndex = this.theIndex;
			this.theIndex = null;
			//初始坐标
			this.initXY = [event.touches[0].pageX, event.touches[0].pageY];
		},

		touchMove(index, event) {
			//多点触控不触发
			if (event.touches.length > 1) {
				this.isStop = true;
				return;
			}
			let moveX = event.touches[0].pageX - this.initXY[0];
			let moveY = event.touches[0].pageY - this.initXY[1];

			if (this.isStop || Math.abs(moveX) < 5) {
				return;
			}
			if (Math.abs(moveY) > Math.abs(moveX)) {
				// 竖向滑动-不触发左滑效果
				this.isStop = true;
				return;
			}

			if (moveX < 0) {
				this.theIndex = index;
				this.isStop = true;
			} else if (moveX > 0) {
				if (this.theIndex != null && this.oldIndex == this.theIndex) {
					this.oldIndex = index;
					this.theIndex = null;
					this.isStop = true;
					setTimeout(() => {
						this.oldIndex = null;
					}, 150);
				}
			}
		},

		touchEnd(index, $event) {
			//结束禁止触发效果
			this.isStop = false;
		},
		/** 控制左滑删除效果 end */

		//商品跳转
		toGoods(goodsId) {
			uni.navigateTo({
				url: `/pages/goods/goodsDetail?goodsId=${goodsId}`
			});
		},

		//跳转确认订单页面
		toConfirmation() {
			if (this.selectedList.length < 1) {
				uni.showToast({
					title: "请选择商品结算",
					icon: "none"
				});
				return;
			}
			const buyData = JSON.stringify({
				cartIds: this.selectedList.join(",")
			});
			uni.navigateTo({
				url: `/pages/user/pages/order/createOrder?buyData=${buyData}`
			});
		},

		/** 删除购物车商品 begin */
		// 删除购物车商品
		async onDeleteCustomerCart(cartId, index) {
			try {
				await this.$api.showModal({
					showCancel: true,
					content: "确认删除当前购物车？"
				});
			} catch (error) {
				console.log("error", error);
				return;
			}

			const propsData = {
				ids: (cartId && cartId.split(",")) || this.selectedList
			};

			try {
				const res = await deleteBatchCart(propsData);
				uni.showToast({
					title: res.resultInfo,
					duration: 1500
				});

				// 是否单个删除
				if (cartId) {
					this.removeGoods(cartId, index);
				} else {
					this.removeCartList();
				}

				this.calcPriceTotal();
				this.oldIndex = null;
				this.theIndex = null;
				this.getCartCount();
			} catch (error) {
				console.log("error", error);
				uni.showToast({
					title: error.resultInfo,
					duration: 1500,
					icon: "none"
				});
			}
		},

		//删除单个商品
		removeGoods(cartId, index) {
			this.cartList.splice(index, 1);
			this.selectedList.splice(this.selectedList.indexOf(cartId), 1);
		},

		// 删除多个商品
		removeCartList() {
			for (const cartId of this.selectedList) {
				this.cartList.forEach((item, index) => {
					if (item.cartId == cartId) {
						this.cartList.splice(index, 1);
					}
				});
			}
			this.selectedList = [];
			this.isAllselected =
				this.selectedList.length == this.cartList.length &&
				this.cartList.length > 0;
		},
		/** 删除购物车商品 end */

		// 选中商品
		selectedCart(goods) {
			uni.showLoading();
			if (goods.isEffective !== 1) {
				this.$api.showToast("该商品已失效");
				return;
			}
			const selectedList = this.selectedList;
			goods.checked = !goods.checked;
			let i = selectedList.indexOf(goods.cartId);
			i > -1
				? selectedList.splice(i, 1)
				: selectedList.push(goods.cartId);
			this.isAllselected = selectedList.length == this.cartList.length;
			this.calcPriceTotal();
		},

		//全选
		allSelectGoods() {
			uni.showLoading();
			const arr = [];

			for (const goods of this.cartList) {
				if (goods.isEffective !== 1) {
					continue;
				}
				goods.checked = this.isAllselected ? false : true;
				arr.push(goods.cartId);
			}
			this.selectedList = this.isAllselected ? [] : arr;
			this.isAllselected =
				this.isAllselected || this.selectedList.length == 0
					? false
					: true;
			this.calcPriceTotal();
		},

		/** 修改购买数量区域 begin */
		/**
		 * @param { Number } index	// 当前购物车索引
		 * @param { Number } buyNubmer	// 购买数量
		 */
		async onUpdGoodsToCart(index, buyNubmer) {
			const goods = this.cartList[index];
			const propsData = {
				cartId: goods.cartId,
				number: buyNubmer,
				skuId: goods.skuId,
				showLoading: false,
				hideLoading: false
			};

			await updateCart(propsData);
			await this.calcPriceTotal();
		},

		// 减少数量
		async subBuyNum(index) {
			uni.showLoading({ title: "", mask: true });
			const goods = this.cartList[index];
			if (goods.number <= 1) {
				goods.number = 1;
				this.$api.showToast("不能再少了 * _ *");
				return;
			}
			try {
				await this.onUpdGoodsToCart(index, goods.number - 1);
				goods.number--;
				uni.hideLoading();
				// this.calcPriceTotal();
			} catch (error) {
				console.log("error", error);
				uni.hideLoading();
				uni.showToast({
					title: error.resultInfo,
					icon: "none"
				});
			}
			// goods.number--;
		},

		// 增加数量
		async addBuyNum(index) {
			uni.showLoading({ title: "", mask: true });
			const goods = this.cartList[index];
			console.log("goods", goods);
			if (goods.number >= goods.stock) {
				goods.number = goods.stock;
				this.$api.showToast("不能再加了 * _ *");
				return;
			}
			try {
				await this.onUpdGoodsToCart(index, goods.number + 1);
				goods.number++;
				uni.hideLoading();
				// this.calcPriceTotal();
			} catch (error) {
				console.log("error", error);
				uni.hideLoading();
				uni.showToast({
					title: error.resultInfo,
					icon: "none"
				});
			}
			// goods.number++;
		},

		// 改变购买数量
		ranDomBuyNum(index) {
			uni.showLoading({ title: "", mask: true });
			// setTimeout是为了防止input值不改变（详见uniapp）
			const goods = this.cartList[index];

			// 最大购买数量
			if (goods.number > goods.stock) {
				setTimeout(() => {
					goods.number = goods.stock;
				}, 0);
			}

			// 最小购买数量
			if (goods.number < 1) {
				setTimeout(() => {
					goods.number = 1;
				}, 0);
			}

			setTimeout(() => {
				this.onUpdGoodsToCart(index, goods.number)
					.then(res => {
						uni.hideLoading();
					})
					.catch(error => {
						console.log("error", error);
						uni.hideLoading();
						this.$api.showToast(error.resultInfo || "操作失败");
					});
			}, 10);
		}
		/** 修改购买数量区域 end */

		// 合计
		// sumBuyPrice() {
		//   this.sumPrice = 0;
		//   for (const goods of this.cartList) {
		//     if (goods.checked) {
		//       this.sumPrice = this.sumPrice + goods.number * goods.price;
		//     }
		//   }
		//   this.sumPrice = this.sumPrice.toFixed(2);
		// }
	}
};
</script>

<style lang="scss" scoped>
@import "@/pages/tabbar/styles/cart.scss";
</style>
